package com.onlyphoto.onlymall.mvp.view.fragment

import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.database.sqlite.SQLiteDatabase
import com.onlyphoto.onlymall.R
import com.onlyphoto.onlymall.base.BaseFragment
import com.onlyphoto.onlymall.mvp.contract.CHomePage
import com.onlyphoto.onlymall.mvp.presenter.PHomePageImpl

import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.onlyphoto.onlymall.bean.ProductBean
import com.onlyphoto.onlymall.bean.request.GoodsCondition
import com.onlyphoto.onlymall.bean.response.GoodsBean
import com.onlyphoto.onlymall.bean.response.Rotation
import com.onlyphoto.onlymall.bean.response.SingleActivityBean
import com.onlyphoto.onlymall.events.ChangeTabEvent
import com.onlyphoto.onlymall.mvp.view.activity.RaidersActivity
import com.onlyphoto.onlymall.mvp.view.activity.SearchActivity
import com.onlyphoto.onlymall.mvp.view.adapter.GoodsAdapter
import com.onlyphoto.onlymall.sqlite.OnlyMallSQLiteOpenHelper
import com.onlyphoto.onlymall.utils.*
import com.onlyphoto.onlymall.widget.BannerLayout
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import kotlinx.android.synthetic.main.fragment_homepage.*
import org.greenrobot.eventbus.EventBus
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram
import com.onlyphoto.onlymall.BuildConfig
import com.tencent.mm.opensdk.openapi.WXAPIFactory




class HomePageFragment : BaseFragment<PHomePageImpl>(), CHomePage.IVHomePage, OnRefreshListener, View.OnClickListener{

    private var adapter: GoodsAdapter? = null
    private var database: SQLiteDatabase? = null
    private val logTag = "MainActivity"
    var bean: SingleActivityBean? = null

    override fun retry() {
        loadData()
    }

    private fun initRv(){
        val layoutManager = LinearLayoutManager(activity)

        rv_home.layoutManager = layoutManager
        adapter = GoodsAdapter()
        rv_home.adapter = adapter
    }

    private fun initListener(){
        fl_search.setOnClickListener(this)
        single_activity.setOnClickListener(this)
        ll_region.setOnClickListener(this)
        ll_menu1.setOnClickListener(this)
        ll_menu2.setOnClickListener(this)
        ll_menu3.setOnClickListener(this)
        ll_menu4.setOnClickListener(this)
        ll_menu5.setOnClickListener(this)
    }

    private fun initRefreshLayout(){
        srl_home.isEnableLoadmore = false
        srl_home.setDisableContentWhenRefresh(true)
        srl_home.setOnRefreshListener(this)
    }

    override fun setCondition(): GoodsCondition {
        val goodsCondition = GoodsCondition()
        goodsCondition.condition = "1"
        return goodsCondition
    }

    override fun requestRotationSuccess(list: ArrayList<Rotation>) {
        bl_home.setImageLoader(GlideImageLoader())
        val urls = java.util.ArrayList<String>()
        if (!CollectionUtils.isEmpty(list)) {
            for (rotation in list) {
                urls.add(rotation.img_url)
            }
        }
        bl_home.setViewUrls(urls)
        bl_home.setOnBannerItemClickListener { position ->
            EventBus.getDefault().post(list[position])
        }
    }

    override fun requestActivitySingleSuccess(bean: SingleActivityBean) {
        Glide.with(activity!!).load(bean.img_url).placeholder(R.mipmap.img_default).into(single_activity)
        this.bean = bean
    }

    override fun requestGoodsSuccess(list: ArrayList<GoodsBean>) {
        adapter?.setItemData(list)
    }

    private fun loadData(){
        mPresenter!!.requestRotation()
        mPresenter!!.requestActivitySingle(1, 0)
        mPresenter!!.requestGoods()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.fl_search -> {
                startActivity(Intent(activity, SearchActivity::class.java))
            }
            R.id.single_activity ->
                EventBus.getDefault().post(bean)
            R.id.ll_region ->
                EventBus.getDefault().post(ChangeTabEvent(Constants.PAGE_CATEGORY_INDEX))
            R.id.ll_menu1 -> {
                EventBus.getDefault().post(ChangeTabEvent(Constants.PAGE_CATEGORY_INDEX))
                EventBus.getDefault().post("12")
            }
            R.id.ll_menu2 -> turnToMinProgram("pages/crowdfunding_list/crowdfunding_list")
            R.id.ll_menu3 -> startActivity(Intent(activity, RaidersActivity::class.java))
            R.id.ll_menu4 -> turnToMinProgram("pages/index/index")
            R.id.ll_menu5 -> {
                EventBus.getDefault().post(ChangeTabEvent(Constants.PAGE_CATEGORY_INDEX))
                EventBus.getDefault().post("18")
            }
        }
    }

    private fun turnToMinProgram(path: String){
        val appId = BuildConfig.WEIXIN_APPID // 填应用AppId
        val api = WXAPIFactory.createWXAPI(context, appId)

        val req = WXLaunchMiniProgram.Req()
        req.userName = Constants.MIN_USERNAME // 填小程序原始id
        req.path = path                  ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
        req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE// 可选打开 开发版，体验版和正式版
        api.sendReq(req)
    }

    override fun init() {
        Glide.with(activity!!).asGif().load(R.mipmap.home_menu5).into(iv_menu5)

        initRv()
        initRefreshLayout()
        initListener()
        loadData()
        val helper = OnlyMallSQLiteOpenHelper(activity)
        database = helper.writableDatabase
    }

    override fun onRefresh(refreshlayout: RefreshLayout?) {
        loadData()
    }

    override fun getLayoutRes(): Int {
        return R.layout.fragment_homepage
    }

    override fun createPresenter() {
        mPresenter = PHomePageImpl(mContext, this)
    }

    override fun showLoading() {
        //showDefaultDialog()
    }

    override fun hideLoading() {
        srl_home.finishRefresh()
        //hideDefaultDialog()
    }

    private fun createProduct(i: Int): ProductBean {
        val product = ProductBean()
        product.id = i
        product.name = "product_$i"
        product.in_store = 888
        return product
    }

    private fun productToContentValues(product: ProductBean): ContentValues {
        val values = ContentValues()
        values.put("id", product.id)
        values.put("name", product.name)
        values.put("in_store", product.in_store)
        return values
    }

    private fun insertProducts() {
        for (i in 1..5) {
            val values = productToContentValues(createProduct(i))
            database!!.insert(OnlyMallSQLiteOpenHelper.TABLE_PRODUCTS, null, values)
        }
    }

    private fun queryProducts() {

        // 相当于 select * from products 语句
        val cursor = database!!.query(OnlyMallSQLiteOpenHelper.TABLE_PRODUCTS, null,
                "id >= 1", null, null, null, null, null)

        // 不断移动光标获取值
        while (cursor.moveToNext()) {
            // 直接通过索引获取字段值
            val proId = cursor.getInt(0)

            // 先获取 name 的索引值，然后再通过索引获取字段值
            val proName = cursor.getString(cursor.getColumnIndex("name"))
            LogUtil.log(logTag, "id: $proId name: $proName")
        }
        // 关闭光标
        cursor.close()
    }

    private fun deleteProducts() {
        database!!.delete(OnlyMallSQLiteOpenHelper.TABLE_PRODUCTS,
                "id = ?", arrayOf("1"))
    }

    private fun updateProducts() {
        val contentValues = ContentValues()
        contentValues.put("name", "apple")
        database!!.update(OnlyMallSQLiteOpenHelper.TABLE_PRODUCTS,
                contentValues, "id = 1", null)
    }

    class GlideImageLoader : BannerLayout.ImageLoader {

        override fun displayImage(context: Context, path: String, imageView: ImageView) {
            Glide.with(context).load(path).placeholder(R.mipmap.img_default).dontAnimate().transform(GlideRoundTransform(20)).into(imageView)
        }
    }

    companion object {

        fun newInstance(): HomePageFragment {
            val fragment = HomePageFragment()
            val args = Bundle()
            fragment.arguments = args
            return fragment
        }
    }
}
